<template>
  <div class="app-container">
    <el-form ref="queryRef" :model="queryParams" :inline="true" label-width="68px" v-show="showSearch">
      <el-form-item label="分类">
        <!-- categoryIdList保存着选中三个级别的分类的id    categoryIdList = [1,2,3] -->
        <el-cascader
            :props="categoryProps"
            style="width: 100%"
            v-model = "categoryIdList"
        />
      </el-form-item>

      <el-form-item label="品牌">
        <el-select
            class="m-2"
            placeholder="选择品牌"
            size="small"
            style="width: 100%"
            v-model ="queryParams.brandId"
        >
          <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="queryHandle">搜索</el-button>
        <el-button icon="Refresh" id="reset-all" @click="queryReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click ="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- 功能按钮栏 -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据展示表格 -->
    <el-table :data="categoryBrandList" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类名称" prop="categoryName" />
      <el-table-column label="品牌名称" prop="brandName" />
      <el-table-column prop="logo" label="品牌图标" #default="scope">
        <img :src="scope.row.logo" width="50" />
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />


    <!-- 添加或修改分类品牌对话框 -->
    <el-dialog :title="title" v-model="open" :rules="rules" width="500px" append-to-body>
      <el-form ref="categoryBrandRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类" prop="categoryIdList">
          <el-cascader
              :props="categoryProps"
              v-model="form.categoryIdList"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select
              v-model="form.brandId"
              class="m-2"
              placeholder="选择品牌"
              size="small"
          >
            <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="CategoryBrand">
import { listCategoryBrand,addCategoryBrand,getCategoryBrand,updateCategoryBrand,deleteCategoryBrand } from '@/api/product/categoryBrand'
import { treeSelect } from '@/api/product/category'
import { getBrandAll } from '@/api/product/brand'


// ================数据模型定义  start ===============================================

const { proxy } = getCurrentInstance();

// 定义搜索表单数据模型
const brandList = ref([])

const props = {
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  async lazyLoad(node, resolve) {   // 加载数据的方法
    //debugger
    if(typeof node.value == 'undefined'){
      node.value = 0
    }

    const { code,msg,data } = await treeSelect(node.value);

    data.forEach(item=>{
      item.leaf = !item.hasChildren
    })

    resolve(data)  // 返回数据
  }
};
const categoryProps = ref(props)

// 定义表格数据模型
const categoryBrandList = ref([])

// 分页条数据模型
const total = ref(0)

//搜索的分类id集合
const categoryIdList = ref([])

const data = reactive({
  queryParams:{
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    brandId: null
  },
  rules: {
    categoryIdList: [
      { required: true, message: "分类不能为空", trigger: "change" }
    ],
    brandId: [
      { required: true, message: "品牌不能为空", trigger: "change" }
    ]
  },
  form: {
    id: null,
    categoryIdList: [],
    brandId: null,
    categoryId: null,
  }
})

const { queryParams,form,rules }  = toRefs(data)

const loading = ref(false)

const showSearch = ref(true)

const title = ref('')
const open = ref(false)


const ids = ref([])
const single = ref(true)
const multiple = ref(true)

// =========   数据模型定义 end======================================================================



// ================函数定义  start ===============================================
function getList(){
  loading.value = true
  if(categoryIdList.value.length ==3){
    queryParams.value.categoryId =  categoryIdList.value[2]
  }

  listCategoryBrand(queryParams.value).then(result=>{
    categoryBrandList.value = result.rows
    total.value = result.total
    loading.value = false
  })
}
getList();

function getBrandList(){
  getBrandAll().then(result=>{
    brandList.value = result.data
  })
}

getBrandList()

function queryHandle(){
  getList();
}

function queryReset(){
  categoryIdList.value = []
  proxy.resetForm('queryRef')
  queryParams.value.brandId = null
  queryParams.value.pageNum  = 1
  queryParams.value.pageSize = 10
  getList()
}
//-----------------------------------
function resetForm(){
  proxy.resetForm('categoryBrandRef')
  form.value.categoryIdList = []
  form.value.brandId = null
  form.value.categoryId = null
}

function handleAdd(){
  open.value = true
  resetForm()
}
//添加或修改
function submitForm(){

  proxy.$refs['categoryBrandRef'].validate(valid=>{



    if(valid){
      form.value.categoryId = form.value.categoryIdList[2]
      if(form.value.id==null){
        addCategoryBrand(form.value).then(result=>{
          open.value = false
          proxy.$modal.msgSuccess(result.msg)
          getList()
        })
      }else{
        updateCategoryBrand(form.value).then(result=>{
          open.value = false
          proxy.$modal.msgSuccess(result.msg)
          getList()
        })
      }

    }else{
      proxy.$modal.msgError("表单校验失败")
    }
  })


}

function cancel(){
  open.value = false
  resetForm();
}

//------------------------------------

function handleUpdate(row){
  open.value = true
  let _id = row.id || ids.value
  getCategoryBrand(_id).then(result=>{
    form.value = result.data
  })
}

function handleSelectionChange(selection){
  ids.value = selection.map(item=>item.id)
  single.value = selection.length != 1
  multiple.value = selection.length==0
}

//--------------------------------------

function handleDelete(row){
  let _id = row.id || ids.value
  proxy.$modal.confirm('您确定要删除数据吗?').then(()=>{
    return deleteCategoryBrand(_id)
  }).then(()=>{
    open.value = false
    proxy.$modal.msgSuccess('删除成功')
    getList()
  }).catch((e)=>{
    if('cancel' === e){
      proxy.$modal.msgSuccess('取消删除')
    }else{
      proxy.$modal.msgError('删除失败')
    }
  })
}


// =============== 函数定义 end======================================================================

</script>



